package com.sourceQ.system.service.message.sms.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.sourceQ.common.core.utils.bean.BeanUtils;
import com.sourceQ.common.security.utils.DictUtils;
import com.sourceQ.common.sms.core.client.SmsClient;
import com.sourceQ.common.sms.core.client.SmsClientFactory;
import com.sourceQ.common.sms.core.property.SmsChannelProperties;
import com.sourceQ.system.domain.message.sms.SysSmsChannel;
import com.sourceQ.system.dto.message.SmsChannelPageReqDTO;
import com.sourceQ.system.dto.message.SmsChannelSaveReqDTO;
import com.sourceQ.system.mapper.message.sms.SysSmsChannelMapper;
import com.sourceQ.system.service.message.sms.SysSmsChannelService;
import com.sourceQ.system.service.message.sms.SysSmsTemplateService;
import com.sourceQ.system.vo.sms.SmsChannelVo;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.util.List;

import static com.sourceQ.common.core.constant.ErrorCodeConstants.SMS_CHANNEL_HAS_CHILDREN;
import static com.sourceQ.common.core.constant.ErrorCodeConstants.SMS_CHANNEL_NOT_EXISTS;
import static com.sourceQ.common.core.utils.ExceptionUtil.exception;
import static com.sourceQ.common.core.utils.cache.CacheUtils.buildAsyncReloadingCache;

/**
 * @author: SourceQ
 * @create: 2024-04-24 11:32
 * @Description:
 */
@Service
@Slf4j
public class SysSmsChannelServiceImpl extends ServiceImpl<SysSmsChannelMapper, SysSmsChannel> implements SysSmsChannelService {
    /**
     * {@link SmsClient} 缓存，通过它异步刷新 smsClientFactory
     */
    @Getter
    private final LoadingCache<Long, SmsClient> idClientCache = buildAsyncReloadingCache(Duration.ofSeconds(10L),
            new CacheLoader<Long, SmsClient>() {

                @Override
                public SmsClient load(Long id) {
                    // 查询，然后尝试刷新
                    SysSmsChannel channel = baseMapper.selectById(id);
                    if (channel != null) {

                        SmsChannelProperties properties = BeanUtils.toBean(channel, SmsChannelProperties.class);
                        smsClientFactory.createOrUpdateSmsClient(properties);
                    }
                    return smsClientFactory.getSmsClient(id);
                }

            });

    /**
     * {@link SmsClient} 缓存，通过它异步刷新 smsClientFactory
     */
    @Getter
    private final LoadingCache<String, SmsClient> codeClientCache = buildAsyncReloadingCache(Duration.ofSeconds(60L),
            new CacheLoader<String, SmsClient>() {

                @Override
                public SmsClient load(String code) {
                    // 查询，然后尝试刷新
                    SysSmsChannel channel = baseMapper.selectOne(Wrappers.<SysSmsChannel>lambdaQuery().eq(SysSmsChannel::getCode,code));
                    if (channel != null) {
                        SmsChannelProperties properties = BeanUtils.toBean(channel, SmsChannelProperties.class);
                        smsClientFactory.createOrUpdateSmsClient(properties);
                    }
                    return smsClientFactory.getSmsClient(code);
                }

            });

    @Autowired
    private SmsClientFactory smsClientFactory;
    @Autowired
    @Lazy
    private SysSmsTemplateService smsTemplateService;

    @Override
    public Long createSmsChannel(SmsChannelSaveReqDTO createReqVO) {
        SysSmsChannel channel = BeanUtils.toBean(createReqVO, SysSmsChannel.class);
        baseMapper.insert(channel);
        return channel.getId();
    }

    @Override
    public void updateSmsChannel(SmsChannelSaveReqDTO updateReqVO) {
        SysSmsChannel channel = validateSmsChannelExists(updateReqVO.getId());
        // 更新
        SysSmsChannel updateObj = BeanUtils.toBean(updateReqVO, SysSmsChannel.class);
        baseMapper.updateById(updateObj);

        // 清空缓存
        clearCache(updateReqVO.getId(), channel.getCode());
    }

    @Override
    public void deleteSmsChannel(Long id) {
        SysSmsChannel channel = validateSmsChannelExists(id);
        // 校验是否有在使用该账号的模版
        if (smsTemplateService.getSmsTemplateCountByChannelId(id) > 0) {
            throw exception(SMS_CHANNEL_HAS_CHILDREN);
        }
        // 删除
        baseMapper.deleteById(id);
        // 清空缓存
        clearCache(id, channel.getCode());
    }

    @Override
    public SysSmsChannel getSmsChannel(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<SmsChannelVo> getSmsChannelList() {
        List<SysSmsChannel> sysSmsChannels = baseMapper.selectList(new QueryWrapper<>());
        List<SmsChannelVo> vos = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(sysSmsChannels)) {
            vos = BeanUtils.copyAnyProperties(sysSmsChannels,SmsChannelVo.class);
            vos.forEach(vo->{
                vo.setCodeName(DictUtils.getDictLabel("sys_sms_channel",vo.getCode()));
                vo.setStatusName(DictUtils.getDictLabel("sys_tenant_package_status",vo.getStatus()));
            });
        }
        return vos;
    }

    @Override
    public IPage<SysSmsChannel> getSmsChannelPage(Page page, SmsChannelPageReqDTO pageReqVO) {
        return baseMapper.page(page, pageReqVO);
    }

    @Override
    public SmsClient getSmsClient(Long id) {
        return idClientCache.getUnchecked(id);
    }

    @Override
    public SmsClient getSmsClient(String code) {
        return codeClientCache.getUnchecked(code);
    }

    /**
     * 校验短信渠道是否存在
     * @param id
     * @return
     */
    private SysSmsChannel validateSmsChannelExists(Long id) {
        SysSmsChannel channel = baseMapper.selectById(id);
        if (channel == null) {
            throw exception(SMS_CHANNEL_NOT_EXISTS);
        }
        return channel;
    }
    /**
     * 清空指定渠道编号的缓存
     *
     * @param id 渠道编号
     * @param code 渠道编码
     */
    private void clearCache(Long id, String code) {
        idClientCache.invalidate(id);
        if (StrUtil.isNotEmpty(code)) {
            codeClientCache.invalidate(code);
        }
    }
}
